<?php

namespace S\WeChat\Util;

/**
 * 序列化器
 *
 * @package Ext\Wechat\Util
 */
class Serializer
{

    const TO_OBJECT = false;
    const TO_ARRAY  = true;

    public static function encode($data)
    {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    public static function decode($string, $to = self::TO_ARRAY)
    {
        if (empty($string)) {
            return null;
        }
        $decoded = json_decode($string, $to);
        if (null === $decoded) {
            $decoded = json_decode(preg_replace('/"(city|province|country)":"[^"]+"/', '"\\1":""', $string), $to);
        }
        if (null === $decoded) {
            $decoded = json_decode(preg_replace('/"nickname":"[^"]+"/', '"nickname":"UNKNOW_CHARS"', $string), $to);
        }
        return $decoded;
    }
}